//
//  RBWebExeView.m
//  jhShop
//
//  Created by Lan on 2019/6/27.
//  Copyright © 2019 SummerTea. All rights reserved.
//

#import "RBWebExeView.h"
#import <WebKit/WebKit.h>
#import <Masonry.h>
#import "RBThemeConfig.h"
#import "RBURLConfig.h"
#import <UIView+YYAdd.h>
#import "UIViewController+RBAdd.h"

#define kJumpPre @"rb_pic_jump"

@interface RBWebExeView()<WKUIDelegate, WKNavigationDelegate>

@property (strong, nonatomic) WKWebView *webview;
@property(nonatomic, assign) CGFloat lineHeight;
@property(nonatomic, strong) UIView *lineView;
@property(nonatomic, assign) CGFloat leftRightPadding;
@property(nonatomic, strong) UIActivityIndicatorView *indicatorView;

@end

@implementation RBWebExeView

#pragma mark - System

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.clipsToBounds = YES;
        self.masAutoUpdateHeight = YES;
        _fold = YES;
        self.currentHeight = 30;
    }
    return self;
}

- (void)dealloc
{
    [_webview.scrollView removeObserver:self forKeyPath:@"contentSize"];
    [_webview removeObserver:self forKeyPath:@"estimatedProgress"];
}

#pragma mark - Public

+ (instancetype)viewWithBottomLineHeight:(CGFloat)lineHeight leftRightPadding:(CGFloat)leftRightPadding
{
    RBWebExeView *view = [RBWebExeView new];
    view.lineHeight = lineHeight;
    if (view.lineHeight > 0)
    {
        view.lineView.hidden = NO;
    }
    view.leftRightPadding = leftRightPadding - 7;
    return view;
}

- (void)setHtmlString:(NSString *)htmlString
{
    self.indicatorView.hidden = NO;
    [self.indicatorView startAnimating];
    
    if (![htmlString containsString:@"<p>"])
    {
        htmlString = [NSString stringWithFormat:@"<p>%@<\/p>", htmlString];
    }
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"<img" withString:@"<img onclick='show(this.src)' "];
    
    NSString *newHtmlString = [NSString stringWithFormat:@"<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'><meta name='apple-mobile-web-app-capable' content='yes'><meta name='apple-mobile-web-app-status-bar-style' content='black'><meta name='format-detection' content='telephone=no'><script>function show(s){document.location = '%@'+s;}</script><style type='text/css'>img{width:100%%}p{font-size:13px;line-height:22px;color:#333333}</style>%@", kJumpPre, htmlString];

//    NSString *newHtmlString = [NSString stringWithFormat:@"<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'><meta name='apple-mobile-web-app-capable' content='yes'><meta name='apple-mobile-web-app-status-bar-style' content='black'><meta name='format-detection' content='telephone=no'><style type='text/css'>img{width:100%%}p{font-size:13px;line-height:22px;color:#333333}</style>%@", htmlString];
    
    [self.webview loadHTMLString:newHtmlString baseURL:[NSURL URLWithString:[[RBURLConfig shareInstance] commonServicePicUrl]]];
    
    [self bringSubviewToFront:self.indicatorView];
    _lineView.hidden = YES;
}

- (void)setUrl:(NSString *)url
{
    [self.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
    [self bringSubviewToFront:self.indicatorView];
    _lineView.hidden = YES;
}

#pragma mark - Event

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"contentSize"])
    {
        self.currentHeight = MAX(self.webview.scrollView.contentSize.height + self.lineHeight, 30);
        [self.webview mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(MAX(self.webview.scrollView.contentSize.height, 10));
        }];
        if (self.masAutoUpdateHeight && !self.fold)
        {
            [self mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(self.currentHeight);
            }];
        }
        if (self.heightChangeBlock)
        {
            self.heightChangeBlock(self.currentHeight);
        }
    }
    else if([keyPath isEqualToString:@"estimatedProgress"])
    {
        if (self.webview.estimatedProgress > 0.1)
        {
            [self.indicatorView stopAnimating];
            self.indicatorView.hidden = YES;
            _lineView.hidden = NO;
        }
    }
}

#pragma mark - Delegate

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation

{
    
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSString *path = navigationAction.request.URL.absoluteString;
    path = [path stringByReplacingOccurrencesOfString:[[RBURLConfig shareInstance] commonServicePicUrl] withString:@""];
    if ([path hasPrefix:kJumpPre])
    {
        path = [path stringByReplacingOccurrencesOfString:kJumpPre withString:@""];
        path = [RBURLConfig adjustImageUrl:path];
        [self.viewController showWithImages:@[path] index:0 imageViews:nil];
        decisionHandler(WKNavigationActionPolicyCancel);
    }
    else
    {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}
#pragma mark - Setter

- (void)setFold:(BOOL)fold
{
    _fold = fold;
    if (self.superview)
    {
        if (fold)
        {
            [self mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(0);
            }];
        }
        else
        {
            [self mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(self.currentHeight);
            }];
        }
    }
}

#pragma mark - Getter

- (WKWebView *)webview
{
    if (!_webview)
    {
        self.webview = ({
            WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
            WKWebView *view = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
            view.UIDelegate = self;
            view.navigationDelegate = self;
            
            view.backgroundColor = [UIColor whiteColor];
            view.allowsBackForwardNavigationGestures = YES;
            view.scrollView.scrollEnabled = NO;
            [view.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:NULL];
            [view addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
            
            [self addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(0);
                make.left.mas_equalTo(self.leftRightPadding);
                make.right.mas_equalTo(-self.leftRightPadding);
                make.height.mas_equalTo(10);
            }];
            view;
        });
    }
    return _webview;
}

- (UIView *)lineView
{
    if (!_lineView)
    {
        self.lineView = ({
            UIView *view = [UIView new];
            view.backgroundColor = [RBThemeConfig bgGrayColor];
            [self addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.mas_equalTo(0);
                make.height.mas_equalTo(self.lineHeight);
            }];
            view;
        });
    }
    return _lineView;
}

- (UIActivityIndicatorView *)indicatorView
{
    if (!_indicatorView)
    {
        self.indicatorView = ({
            UIActivityIndicatorView *view = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            [self addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.height.mas_equalTo(15);
                make.center.mas_equalTo(0);
            }];
            
            view;
        });
    }
    return _indicatorView;
}

@end
